package com.kdtech.analyse.app;
import java.util.HashMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;

/**
 * @author dhy
 * @name 海湾新闻
 * @link http://appserver.haiwainet.cn/
 */
public class HaiwainetAppAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://m.haiwainet.cn/phone/[0-9]+/[0-9]+/[0-9]+/content_[0-9]+_1.html",
	};

	public static HashMap<String, String> getLinks(String url){
		HashMap<String, String> links = new HashMap<String, String>();
		
		try{
			String htmltxt = null;
			if(StringUtils.isNotBlank(htmltxt)){
				JSONObject jObj = JSONObject.parseObject(htmltxt);
				JSONArray newsList = JSONArray.parseArray(JSONObject.parseObject(jObj.getString("data")).getString("newsList"));
				for(int i = 0; i < newsList.size(); i++){	
					try{
						String link = newsList.getJSONObject(i).getString("newsLink");
						links.put(link, "");
					}catch(Exception e){
						continue;
					}
				}
			}
		}catch(Exception e){
			
		}
		return links;
	}
	
	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		
		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title =doc.select("h1").text();
		if(StringUtils.isBlank(title))
			title = StringUtils.substringBetween(htmltxt, "\"title\":\"", "\",\"main\":");
		
		date=DateUtils.matchDate(doc.select("time").text());
		if(date==null)
			date=DateUtils.matchDate(url);
		
		content =HtmlCleaner.getContentHtml(url, doc.select("article p"));
		if(StringUtils.isBlank(content))
			content = StringUtils.substringBetween(htmltxt, "\"main\":[", "}");
		
		author=JSoupUtils.matchAuthor(doc, "来源：");
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);

		return news;

	}

	

	

	
}

